package com.authine.cloudpivot.web.api.secondopen.controller;

import cn.hutool.core.bean.BeanUtil;
import com.authine.cloudpivot.engine.api.constants.DingTalkUrlConstants;
import com.authine.cloudpivot.engine.api.model.BaseModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentUserModel;
import com.authine.cloudpivot.engine.api.model.organization.RoleModel;
import com.authine.cloudpivot.engine.api.model.organization.RoleUserModel;
import com.authine.cloudpivot.engine.api.model.organization.UserConditionModel;
import com.authine.cloudpivot.engine.api.model.organization.UserExtAttrModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.organization.UserUnionExtAttrModel;
import com.authine.cloudpivot.engine.api.model.permission.AdminModel;
import com.authine.cloudpivot.engine.api.model.permission.DepartmentScopeModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.api.model.system.RelatedCorpSettingModel;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.type.AdminType;
import com.authine.cloudpivot.engine.enums.type.DeptType;
import com.authine.cloudpivot.engine.enums.type.FileUploadType;
import com.authine.cloudpivot.engine.enums.type.OrgType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.web.api.controller.base.PermissionController;
import com.authine.cloudpivot.web.api.controller.orgnization.SelectionHelper;
import com.authine.cloudpivot.web.api.controller.orgnization.SelectionHelperExt;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import com.authine.cloudpivot.web.api.helper.FileOperateHelper;
import com.authine.cloudpivot.web.api.helper.oraganization.UserHelper;
import com.authine.cloudpivot.web.api.oss.FileStorageConfiguration;
import com.authine.cloudpivot.web.api.oss.OSSClient;
import com.authine.cloudpivot.web.api.secondopen.dao.HOrgRoleUserMapper;
import com.authine.cloudpivot.web.api.task.RunTimeThreadTask;
import com.authine.cloudpivot.web.api.util.ReflectUtil;
import com.authine.cloudpivot.web.api.view.PageVO;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.organization.AdministratorVO;
import com.authine.cloudpivot.web.api.view.organization.DepartmentUserTreeVO;
import com.authine.cloudpivot.web.api.view.organization.DepartmentUserVO;
import com.authine.cloudpivot.web.api.view.organization.DepartmentVO;
import com.authine.cloudpivot.web.api.view.organization.EduClassUserInfoVO;
import com.authine.cloudpivot.web.api.view.organization.EduUserDetailVO;
import com.authine.cloudpivot.web.api.view.organization.UserDetailVO;
import com.authine.cloudpivot.web.api.view.organization.UserInfoVO;
import com.authine.cloudpivot.web.api.view.organization.UserManagerVO;
import com.authine.cloudpivot.web.api.view.organization.UserSelectionVO;
import com.authine.cloudpivot.web.api.view.organization.UserVO;
import com.authine.cloudpivot.web.api.view.runtime.FileOperationResult;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author: brookpeng
 * @Date: 2021/11/19 13:32
 */
@Api(tags = "组织机构::用户")
@RestController
@RequestMapping("/api/organization/user")
@Validated
@CustomizedOrigin(level = 1)
@Slf4j
public class UserControllerNew extends PermissionController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    DubboConfigService dubboConfigService;
    @Autowired
    private OSSClient ossClient;
    @Autowired
    private RunTimeThreadTask springThreadTask;
    @Autowired
    private SelectionHelper selectionHelper;
    @Autowired
    private SelectionHelperExt selectionHelperExt;

    @Autowired
    private HOrgRoleUserMapper hOrgRoleUserMapper;

    @Value("${cloudpivot.bizObject.userQuerySize:100}")
    private Integer organizationUserQuerySize;


    @PostMapping("/search")
    @ApiOperation(value = "查询用户信息", notes = "根据用户名或账户名查询用户信息")
    @ApiImplicitParam(name = "params", value = "{\"wd\":\"关键字\",\"page\":1,\"size\":10,\"filterType\":\"admin(admim端人员搜索过滤，主要为过滤应用管理员的查询范围)\"}", required = true, dataType = "Map")
    public ResponseResult<PageVO<UserVO>> search(@RequestBody Map<String, Object> params) {
        String wd = (String) params.get("wd");
        validateNotEmpty(wd, "关键字不能为空");
        String filterType = (String) params.get("filterType");
        Integer page = (Integer) params.get("page");
        Integer size = (Integer) params.get("size");
        Pageable pageable = PageRequest.of(page == null ? 0 : page, size == null ? 10 : size);

        /* start */
        String loginUserId = getUserId();
        ResponseResult<UserModel> admin = getByUsername("admin");
        String adminId = admin.getData().getId();
        List<Map<String, Object>> userRole = hOrgRoleUserMapper.getUserRole(loginUserId);
        boolean isAdministrator = false;
        if (StringUtils.isNotEmpty(filterType) && "admin".equals(filterType) && loginUserId.equals(adminId)) {
            isAdministrator = true;
        } else {
            for (Map<String, Object> roleModel : userRole) {
                String roleName = (String) roleModel.get("name");
                switch (roleName) {
                    case "集团管理人员":
                        isAdministrator = true;
                        break;
                    case "公司管理人员":
                        isAdministrator = true;
                        break;
                    default:
                        isAdministrator = false;
                }
                if (isAdministrator) {
                    break;
                }
            }
        }
        /* end */

        //应用管理员限制其查询用户在所在的管理范围中
        Set<String> permChildDepartments;
        Set<String> permChildDepartment;
        AdminModel appAdminByUser = getAppAdminByUserId(getUserId());
        if (StringUtils.isNotEmpty(filterType) && "admin".equals(filterType) && appAdminByUser != null && appAdminByUser.getAdminType() == AdminType.APP_MNG) {
            permChildDepartments = getManagePermChildDepartmentId(getUserId());
            //判断部门是否是管理范围里的部门
            List<DepartmentScopeModel> departments = appAdminByUser.getDepartments();
            Set<String> corpIds = new HashSet<>();
            if (!CollectionUtils.isEmpty(departments)) {
                Set<String> departmentIds = departments.stream().filter(departmentScopeModel -> Objects.nonNull(departmentScopeModel.getUnitId())).map(DepartmentScopeModel::getUnitId).collect(Collectors.toSet());
                departmentIds.forEach(s -> {
                    String corpId = getOrganizationFacade().getDepartment(s).getCorpId();
                    corpIds.add(corpId);
                });
            }

            if (permChildDepartments.size() == 0) {
                return getOkResponseResult(new PageVO<>(new PageImpl<>(null, pageable, 0)), "查询用户信息成功");
            } else {
                //判断是否管理组织内部门
                permChildDepartment = permChildDepartments.stream().filter(s -> corpIds.contains(getOrganizationFacade().getDepartment(s).getCorpId())).collect(Collectors.toSet());
            }
        } else {
            permChildDepartment = new HashSet<>();
        }
        //应用管理员管理组织下的人
        Set<String> permUserIdSet = new HashSet<>();

        Map<String, RelatedCorpSettingModel> relatedmap = new HashMap<>();
        getSystemManagementFacade().getAllRelatedCorpSettingModel().stream().forEach(related -> {
            relatedmap.put(related.getCorpId(), related);
        });

        Page<UserModel> userPage = getOrganizationFacade().searchUsersByName(wd, pageable);
        List<UserModel> userList = userPage.getContent();
        /*start*/
        List<UserModel> userListNew = new ArrayList<>();
        userListNew.addAll(userList);
        if (!isAdministrator) {
            for (UserModel userModel : userList) {
                String userId = userModel.getId();
                List<Map<String, Object>> userRoles = hOrgRoleUserMapper.getUserRole(userId);
                boolean isAdministrators = false;
                for (Map<String, Object> roleModel : userRoles) {
                    String roleName = (String) roleModel.get("name");
                    switch (roleName) {
                        case "集团管理人员":
                            isAdministrators = true;
                            break;
                        case "公司管理人员":
                            isAdministrators = true;
                            break;
                        default:
                            isAdministrators = false;
                    }
                    if (isAdministrators) {
                        break;
                    }
                }
                if (isAdministrators) {
                    IntStream.range(0, userListNew.size()).filter(j->userListNew.get(j).getId().equals(userId)).boxed().findFirst().map(j->userListNew.remove((int)j));
                }
            }
        }
        /*end*/
        List<UserVO> userVOList = userListNew.stream().filter(Objects::nonNull).map(user -> {
            List<DepartmentUserModel> deptUserList = getOrganizationFacade().getDepartmentUsersByUserId(user.getId());
            for (DepartmentUserModel deptUser : deptUserList) {
                DepartmentModel departmentModel = getOrganizationFacade().getDepartment(deptUser.getDeptId());
                if (departmentModel != null && StringUtils.isNotEmpty(departmentModel.getManagerId())) {
                    user.setLeader(departmentModel.getManagerId().equals(user.getUserId()));
                } else {
                    Boolean leader = deptUser.getLeader();
                    if (leader) {
                        user.setLeader(true);
                        getOrganizationFacade().updateUser(user);
                    }
                }

                //符合应用管理员管理范围的账户
                if (permChildDepartment.size() > 0 && permChildDepartment.contains(deptUser.getDeptId())) {
                    permUserIdSet.add(deptUser.getUserId());
                }
            }
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);

            RelatedCorpSettingModel corpSettingModel = relatedmap.get(userVO.getCorpId());
            if (corpSettingModel != null) {
                userVO.setRelatedOrgType(corpSettingModel.getOrgType());
                userVO.setRelatedSyncType(corpSettingModel.getSyncType());
            }

            return userVO;
        }).collect(Collectors.toList());
        //根据permChildDepartment是否为0判断是否应用管理员
        List<UserVO> resultList;
        long pagesize = userPage.getTotalElements();
        if (permChildDepartment.size() > 0) {
            resultList = userVOList.stream().filter(user -> permUserIdSet.contains(user.getId())).collect(Collectors.toList());
            //不建议
            pagesize = getOrganizationFacade().searchUsersByName(wd).stream().filter(user -> permUserIdSet.contains(user.getId())).collect(Collectors.toList()).size();
        } else {
            resultList = userVOList;
        }

        setRoleName(resultList);

        if (getOrganizationFacade().getLicensePermGateway()) {
            if (!CollectionUtils.isEmpty(resultList)) {
                List<String> userIds = resultList.stream().filter(Objects::nonNull).map(BaseModel::getId).collect(Collectors.toList());
                Map<String, Boolean> userMaps = getOrganizationFacade().getLicensePermUsersByUserIds(userIds);
                resultList.forEach(item -> {
                    item.setIsAuthUser(userMaps.get(item.getId()));
                });
            }
        }

        Page<UserVO> userVOPage = new PageImpl<>(resultList, pageable, pagesize);

        return getOkResponseResult(new PageVO<UserVO>(userVOPage), "查询用户信息成功");
    }

    @PostMapping("/searchDepartments")
    @ApiOperation(value = "查询部门信息", notes = "根据名称查询部门信息")
    @ApiImplicitParam(name = "params", value = "{\"wd\":\"关键字\",\"page\":1,\"size\":10}", required = true, dataType = "Map")
    public ResponseResult<List<DepartmentModel>> searchDepartments(@RequestBody Map<String, Object> params) {
        String wd = (String) params.get("wd");
        validateNotEmpty(wd, "关键字不能为空");
        return getOkResponseResult(selectionHelperExt.queryDepartments(wd),"查询部门信息");
    }

    @PostMapping("/searchCondiction")
    @ApiOperation(value = "根据名称,用户ID集合，部门ID集合，角色ID集合搜索人", notes = "根据名称,用户ID集合，部门ID集合，角色ID集合搜索人")
    @ApiImplicitParam(name = "params", value = "{\"userName\":\"名称\",\"page\":1,\"size\":10,\"userIds\":\"用户ID集合,\"deptIds\":\"部门ID集合,\"roleIds\":\"角色ID集合", dataType = "Map")
    public ResponseResult<PageVO<UserInfoVO>> searchCondiction(@RequestBody Map<String, Object> map) {

        UserConditionModel userConditionModel = BeanUtil.mapToBean(map, UserConditionModel.class, Boolean.TRUE);
        Page<UserModel> userModelPage = getOrganizationFacade().searchUserWithCondition(userConditionModel, PageRequest.of(userConditionModel.getPage(), userConditionModel.getSize()));
        List<UserInfoVO> userInfoVOS = Lists.newArrayList();
        List<UserModel> userModels = userModelPage.getContent();

        if (!CollectionUtils.isEmpty(userModels)) {
            for (UserModel model : userModels) {
                UserInfoVO vo = new UserInfoVO(model);
                userInfoVOS.add(vo);
            }
        }

        Page<UserInfoVO> userInfoVOPageVO = new PageImpl<>(userInfoVOS, userModelPage.getPageable(), userModelPage.getTotalElements());

        return getOkResponseResult(new PageVO(userInfoVOPageVO), "查询用户信息成功");
    }

    @PostMapping("/searchDemissionUsers")
    @ApiOperation(value = "根据条件搜索离职人员", notes = "根据搜索离职人员列表")
    @ApiImplicitParam(name = "params", value = "{\"wd\":\"关键字\",\"page\":1,\"size\":10}", dataType = "Map")
    public ResponseResult searchDemissionUsers(@RequestBody Map<String, Object> map) {
        String keyword = null;
        Object wd = map.get("wd");
        if (Objects.nonNull(wd)) {
            keyword = String.valueOf(wd);
        }
        Integer page = (Integer) map.get("page");
        Integer size = (Integer) map.get("size");
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        Pageable pageable = PageRequest.of(page, size);
        Page<UserModel> userModelPage = getOrganizationFacade().searchLeaveUsers(keyword, pageable);
        List<UserVO> userVOList = Lists.newArrayList();
        List<UserModel> userModels = userModelPage.getContent();
        if (!CollectionUtils.isEmpty(userModels)) {
            userVOList = userModels.stream().filter(Objects::nonNull).map(userModel -> {
                UserVO vo = new UserVO();
                BeanUtil.copyProperties(userModel, vo);
                return vo;
            }).collect(Collectors.toList());
        }
        Page<UserVO> userVOPage = new PageImpl<>(userVOList, pageable, userModelPage.getTotalElements());
        return getOkResponseResult(userVOPage, "获取组织机构的离职用户成功");
    }


    @GetMapping("/tree/search")
    @ApiOperation(value = "选人控件根据名称搜索人或部门", notes = "选人控件根据名称搜索人或部门")
    @ApiImplicitParam(name = "name", value = "搜索名称", required = true, dataType = "String")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "搜索名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "deptIds", value = "部门编码 “,”分割", required = false, dataType = "String"),
            @ApiImplicitParam(name = "roleIds", value = "角色编码 “,”分割", required = false, dataType = "String"),
            @ApiImplicitParam(name = "corpId", value = "关联组织编码 “,”分割", required = false, dataType = "String"),
            @ApiImplicitParam(name = "filterType", value = "过滤方式 admin admin_corp-应用管理员  main-只显示主部门  self-只显示自维护组织“,”分割", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sourceType", value = "来源类型，admin-后台，portal-门户", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "selectUserIds", value = "选人控件中选中的用户id集合，逗号隔开，用来过滤其所在部门和兼职部门及其下子部门，和当前查询的应用管理员权限取交集", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "formRootDeptIds", value = "表单根部门id", dataType = "String", paramType = "query")
    })
    public ResponseResult<DepartmentUserTreeVO> search(String name, String deptIds, String roleIds,
                                                       @RequestParam(required = false) String filterType,
                                                       @RequestParam(required = false) String corpId, String sourceType,
                                                       String workflowInstanceId, String activityCode, String selectUserIds,
                                                       @RequestParam(required = false) String formRootDeptIds) {
        long begin = System.currentTimeMillis();
        String excludedeptid = null;
        if (StringUtils.isNotEmpty(corpId) && "MAIN_ORG".equals(corpId)) {
            RelatedCorpSettingModel mainCorp = getSystemManagementFacade().getAllRelatedCorpSettingModelByOrgType(OrgType.MAIN).get(0);
            corpId = mainCorp.getCorpId();
        } else if (StringUtils.isNotEmpty(corpId) && corpId.startsWith("userid")) {
            String assignUserId = corpId.replace("userid-", "");
            UserModel u = getOrganizationFacade().getUser(assignUserId);
            corpId = u.getCorpId();
        } else if (StringUtils.isNotEmpty(corpId) && corpId.contains("excludedeptid")) {
            String[] excludedeptidArr = corpId.split("@@excludedeptid-");
            corpId = excludedeptidArr[0];
            excludedeptid = excludedeptidArr[1];
        }

        RelatedCorpSettingModel relatedCorpSettingModel = null;
        if (StringUtils.isNotBlank(sourceType)) {
            UserModel user = getOrganizationFacade().getUser(getUserId());
            relatedCorpSettingModel = getSystemManagementFacade().getRelatedCorpSettingModelByCorpId(user.getCorpId());
        }

        Set<String> permUserIdSet;
        Set<String> managePermChildDepartments;
        Set<String> managePermChildDepartment;
        SelectionHelper.SelectionFilter filterInfo = selectionHelper.relatedSelection(deptIds, filterType, corpId, getUserId());
        Set<String> filterCorpIdSet = filterInfo.getCorpIds();

        if (filterInfo.isNeedFilterAppAdmin()) {
            if (StringUtils.isNotBlank(selectUserIds)) {
                managePermChildDepartment = getLoginUserDeptPermAndSelectUsersMixed(getManagePermChildDepartmentId(getUserId()), selectUserIds);
            } else {
                //需要做应用管理员管理范围过滤
                managePermChildDepartments = getManagePermChildDepartmentId(getUserId());
                AdminModel appAdminByUser = getAppAdminByUserId(getUserId());
                //判断部门是否是管理范围里的部门
                List<DepartmentScopeModel> departments = appAdminByUser.getDepartments();
                Set<String> corpIds = new HashSet<>();
                if (!CollectionUtils.isEmpty(departments)) {
                    Set<String> departmentIds = departments.stream().filter(departmentScopeModel -> Objects.nonNull(departmentScopeModel.getUnitId())).map(DepartmentScopeModel::getUnitId).collect(Collectors.toSet());
                    departmentIds.forEach(s -> {
                        String DepartmentcorpId = getOrganizationFacade().getDepartment(s).getCorpId();
                        corpIds.add(DepartmentcorpId);
                    });
                }
                //判断是否管理组织内部门
                managePermChildDepartment = managePermChildDepartments.stream().filter(s -> corpIds.contains(getOrganizationFacade().getDepartment(s).getCorpId())).collect(Collectors.toSet());

            }
            permUserIdSet = getOrganizationFacade().getUserIdsByDepartmentIds(new ArrayList<>(managePermChildDepartment));
        } else {
            permUserIdSet = new HashSet<>();
            managePermChildDepartment = new HashSet<>();
        }
        final boolean finalNeedFilterCorp = filterInfo.isNeedFilterCorp();
        if (CollectionUtils.isEmpty(getPermissionManagementFacade().getAdminByUserId(getUserId())) && StringUtils.isEmpty(deptIds)) {
            List<DepartmentModel> depts = getOrganizationFacade().getDepartmentsByUserId(getUserId());
            if (depts.stream().noneMatch(dept -> DeptType.DEPT.equals(dept.getDeptType()))) {
                managePermChildDepartment.addAll(getOrganizationFacade().getDepartmentsChildList(depts.stream().map(DepartmentModel::getId).collect(Collectors.toList()), false)
                        .stream().map(DepartmentModel::getId).collect(Collectors.toSet()));
                permUserIdSet.addAll(getOrganizationFacade().getUserIdsByDepartmentIds(new ArrayList<>(managePermChildDepartment)));
                filterInfo.setNeedFilterAppAdmin(true);
            }
        }
        long start = System.currentTimeMillis();
        Set<String> displayDep = new HashSet<>();
        Set<String> depUserIds = new HashSet<>();
        if (StringUtils.isNotBlank(deptIds)) {
            //根据传入的部门id  获取所有部门与旗下的子部门的id（可显示的部门）
            List<String> depIdList = Arrays.asList(deptIds.split(","));
            List<DepartmentModel> leafDepts = getOrganizationFacade().getDepartmentsChildList(depIdList);
            displayDep = leafDepts.stream().map(DepartmentModel::getId).collect(Collectors.toSet());
            depUserIds = getOrganizationFacade().getUserIdsByDepartmentIds(Lists.newArrayList(displayDep));
        }
        final boolean finalNeedFilter = filterInfo.isNeedFilterAppAdmin();

        //搜索部门
        List<DepartmentModel> departmentModelList = getOrganizationFacade().searchDepartmentByDepartmentName(name, true);
        int departmentTotalSize = departmentModelList.size();
        Set<String> finalDisplayDep = displayDep;
        if (!CollectionUtils.isEmpty(departmentModelList)) {
            boolean mainOrg = selectionHelper.isMainOrg();
            departmentModelList = departmentModelList.stream().filter(dept -> {
                boolean nonNull = Objects.nonNull(dept);
                boolean isTrue = mainOrg ? nonNull : nonNull && managePermChildDepartment.contains(dept.getId());
                return (finalNeedFilter ? isTrue : nonNull) && dept.getIsShow();
            })
                    .filter(model -> {
                        if (finalNeedFilterCorp && !filterCorpIdSet.contains(model.getCorpId())) {
                            return false;
                        }
                        if (StringUtils.isBlank(deptIds)) {
                            return true;
                        }
                        return finalDisplayDep.contains(model.getId());
                    })
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(departmentModelList) && relatedCorpSettingModel != null && relatedCorpSettingModel.getOrgType() == OrgType.RELEVANCE) {
                RelatedCorpSettingModel finalRelatedCorpSettingModel = relatedCorpSettingModel;
                departmentModelList = departmentModelList.stream().filter(departmentModel -> finalRelatedCorpSettingModel.getCorpId().equals(departmentModel.getCorpId())).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(departmentModelList) && StringUtils.isNotEmpty(excludedeptid)) {
                String finalExcludedeptid = excludedeptid;
                departmentModelList = departmentModelList.stream().filter(it -> !finalExcludedeptid.equals(it.getId())).collect(Collectors.toList());
            }
            departmentTotalSize = departmentModelList.size();
        }
        if (departmentTotalSize > organizationUserQuerySize) {
            departmentModelList = departmentModelList.subList(0, organizationUserQuerySize);
        }
        long end = System.currentTimeMillis();
        log.info("process time1 : {}", end - start);
        start = end;

        List<DepartmentVO> departmentVOList = null;
        if (!CollectionUtils.isEmpty(departmentModelList)) {
            List<String> deptIdList = departmentModelList.stream().filter(departmentModel -> !(departmentModel.getDeleted())).map(DepartmentModel::getId).collect(Collectors.toList());
            Map<String, List<DepartmentModel>> departmentMap = getOrganizationFacade().getDepartmentsByParentIds(deptIdList, true);
            //加入部门名称
            departmentVOList = departmentModelList.stream().map(departmentModel -> {
                DepartmentVO departmentVO = new DepartmentVO();
                BeanUtils.copyProperties(departmentModel, departmentVO);
                if (departmentMap != null) {
                    List<DepartmentModel> parentDepartments = departmentMap.get(departmentModel.getId());
                    if (!CollectionUtils.isEmpty(parentDepartments)) {
                        String parentDepartmentName = parentDepartments.stream()
                                .sorted(Comparator.comparingInt(o -> -o.getQueryCode().length())).map(DepartmentModel::getName)
                                .collect(Collectors.joining("/"));
                        departmentVO.setParentDepartmentName(parentDepartmentName);
                    }
                }
                return departmentVO;
            }).collect(Collectors.toList());
        }
        end = System.currentTimeMillis();
        log.info("process time2 : {}", end - start);
        start = end;

        //搜索人
        Set<String> roleUserIds = null;
        if (StringUtils.isNotBlank(roleIds)) {
            roleUserIds = getOrganizationFacade().getUserIdsByRoleIds(Arrays.asList(roleIds.split(",")));
        }
        end = System.currentTimeMillis();
        log.info("process time3 : {}", end - start);
        start = end;
        Set<String> displayUser = new HashSet<>();
        if (StringUtils.isNotBlank(deptIds) && StringUtils.isNotBlank(roleIds)) {
            displayUser = roleUserIds;
            displayUser.retainAll(depUserIds);
        } else if (StringUtils.isBlank(deptIds) && StringUtils.isNotBlank(roleIds)) {
            displayUser = roleUserIds;
        } else if (StringUtils.isNotBlank(deptIds) && StringUtils.isBlank(roleIds)) {
            displayUser = depUserIds;
        }
        Set<String> finalDisplayUser = displayUser;
        List<UserModel> userModelList = getOrganizationFacade().searchUsersByName(name, true);
        end = System.currentTimeMillis();
        log.info("process time4 : {}", end - start);
        start = end;
        int userTotalSize = userModelList.size();
        if (!CollectionUtils.isEmpty(userModelList)) {
            boolean mainOrg = selectionHelper.isMainOrg();
            userModelList = userModelList.stream().filter(userModel -> {
                boolean nonNull = Objects.nonNull(userModel);
                boolean isTrue = mainOrg ? nonNull : nonNull && permUserIdSet.contains(userModel.getId());
                return finalNeedFilter ? isTrue : nonNull;
            })
                    .filter(user -> {
                        if (finalNeedFilterCorp && !filterCorpIdSet.contains(user.getCorpId())) {
                            return false;
                        }
                        if (StringUtils.isBlank(deptIds) && StringUtils.isBlank(roleIds)) {
                            return true;
                        }
                        return finalDisplayUser.contains(user.getId());
                    })
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(userModelList) && relatedCorpSettingModel != null && relatedCorpSettingModel.getOrgType() == OrgType.RELEVANCE) {
                RelatedCorpSettingModel finalRelatedCorpSettingModel1 = relatedCorpSettingModel;
                userModelList = userModelList.stream().filter(userModel -> finalRelatedCorpSettingModel1.getCorpId().equals(userModel.getCorpId())).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(userModelList) && StringUtils.isNotEmpty(workflowInstanceId) && StringUtils.isNotEmpty(activityCode)) {
                //所有流程参与者
                Set<String> participants = getWorkflowInstanceFacade().getParticipants(workflowInstanceId, activityCode);
                if (!CollectionUtils.isEmpty(participants)) {
                    userModelList = userModelList.stream().filter(userModel -> !participants.contains(userModel.getId())).collect(Collectors.toList());
                }
            }
            userTotalSize = userModelList.size();
        }
        if (userTotalSize > organizationUserQuerySize) {
            userModelList = userModelList.subList(0, organizationUserQuerySize);
        }
        end = System.currentTimeMillis();
        log.info("process time5 : {}", end - start);
        start = end;
        List<UserSelectionVO> userDetailVOList = null;
        AtomicInteger count = new AtomicInteger(0);
        if (!CollectionUtils.isEmpty(userModelList)) {
            List<String> deptIdList = userModelList.stream().map(UserModel::getDepartmentId).collect(Collectors.toList());
            List<String> userIdList = userModelList.stream().map(UserModel::getId).collect(Collectors.toList());
            Map<String, List<DepartmentModel>> departmentMap = getOrganizationFacade().getDepartmentsByParentIds(deptIdList);
            end = System.currentTimeMillis();
            log.info("process time6 : {}", end - start);
            start = end;
            List<DepartmentUserModel> departmentUserList = getOrganizationFacade().getDepartmentUsersByUserIdsIn(userIdList);
            List<String> allDeptIdList = departmentUserList.stream().map(DepartmentUserModel::getDeptId).collect(Collectors.toList());
            Map<String, DepartmentModel> totalDepartmentMap = getOrganizationFacade().getDepartmentsByDeptIds(allDeptIdList).stream().collect(Collectors.toMap(DepartmentModel::getId, a -> a));
            end = System.currentTimeMillis();
            log.info("process time7 : {}", end - start);
            start = end;
            Map<String, List<RoleModel>> userRoleMap = getOrganizationFacade().getRolesByUserIds(userIdList);
            end = System.currentTimeMillis();
            log.info("process time8 : {}", end - start);
            start = end;
            Map<String, List<DepartmentUserModel>> departmentUserMap = buildDepartmentUserMap(departmentUserList);
            List<String> totalIdList = new ArrayList<>(userIdList);
            totalIdList.addAll(userModelList.stream().map(UserModel::getManagerId).collect(Collectors.toList()));
            totalIdList.addAll(userModelList.stream().map(UserModel::getSecretaryId).collect(Collectors.toList()));
            totalIdList = totalIdList.stream().distinct().collect(Collectors.toList());
            Map<String, UserModel> userMap = getOrganizationFacade().getUsers(totalIdList);
            end = System.currentTimeMillis();
            log.info("process time9 : {}", end - start);
            start = end;
            userDetailVOList = userModelList.stream().map(userModel -> {
                UserSelectionVO userSelectionVO = new UserSelectionVO();
                BeanUtils.copyProperties(userModel, userSelectionVO);
                if (departmentMap != null) {
                    List<DepartmentModel> parentDepartments = departmentMap.get(userModel.getDepartmentId());
                    if (!CollectionUtils.isEmpty(parentDepartments)) {
                        String parentDepartmentName = parentDepartments.stream()
                                .sorted(Comparator.comparingInt(o -> -o.getQueryCode().length())).map(DepartmentModel::getName)
                                .collect(Collectors.joining("/"));
                        userSelectionVO.setParentDepartmentName(parentDepartmentName);
                    }
                }
                final List<SelectionValue> valueList = Lists.newArrayList();
                List<DepartmentUserModel> deptUsers = departmentUserMap.get(userModel.getId());
                if (CollectionUtils.isEmpty(deptUsers)) {
                    deptUsers = getOrganizationFacade().getDepartmentUsersByUserId(userModel.getId());
                    count.incrementAndGet();
                }
                for (DepartmentUserModel deptUser : deptUsers) {
                    DepartmentModel department = totalDepartmentMap.get(deptUser.getDeptId());
                    if (!totalDepartmentMap.containsKey(deptUser.getDeptId())) {
                        department = getOrganizationFacade().getDepartment(deptUser.getDeptId());
                        count.incrementAndGet();
                    }
                    if (Objects.isNull(department)) {
                        continue;
                    }
                    if (!department.getIsShow() || !department.getEnabled()) {
                        continue;
                    }
                    final String departName = Optional.of(department).map(DepartmentModel::getName).orElse(null);
                    final String departId = Optional.of(department).map(DepartmentModel::getId).orElse(null);
                    final SelectionValue selectionValue = new SelectionValue();
                    selectionValue.setId(departId);
                    selectionValue.setName(departName);
                    selectionValue.setType(UnitType.DEPARTMENT);
                    valueList.add(selectionValue);
                }
                userSelectionVO.setDepartments(valueList);
                List<RoleModel> roleModelList = userRoleMap.get(userModel.getId());
                if (!CollectionUtils.isEmpty(roleModelList)) {
                    List<String> roleNameList = roleModelList.stream().filter(Objects::nonNull).map(RoleModel::getName).collect(Collectors.toList());
                    List<String> roleIdList = roleModelList.stream().filter(Objects::nonNull).map(RoleModel::getId).collect(Collectors.toList());
                    if (!roleNameList.isEmpty()) {
                        userSelectionVO.setRoleName(String.join(",", roleNameList));
                        userSelectionVO.setRoleIds(roleIdList);
                    }
                }
                setManagerAndSecretary(userModel, userSelectionVO, userMap, count);


                Map<String, Object> propertiesMap = new HashMap<String, Object>();
                List<UserUnionExtAttrModel> userUnionList = dubboConfigService.getUserExtendFacade().getUnionExtAttrsByUserId(userModel.getId());
                userUnionList.forEach(userUnion -> {
                    UserExtAttrModel userExtAttrModel = dubboConfigService.getUserExtendFacade().getUserExtendByExtendAttrId(userUnion.getExtendAttrId());
                    if (userExtAttrModel != null) {
                        propertiesMap.put(userExtAttrModel.getCode(), userUnion.getMapVal());
                    }
                });
                Object obj = ReflectUtil.getObject(userSelectionVO, propertiesMap);
                return (UserSelectionVO) obj;
            }).collect(Collectors.toList());
        }
        end = System.currentTimeMillis();
        log.info("process time10 : {}", end - start);
        List<DepartmentVO> departmentVOS = selectionHelper.convertDeptFilter(departmentVOList, formRootDeptIds,sourceType);
        List<UserSelectionVO> userSelectionVOS = selectionHelper.convertUserFilter(userDetailVOList,sourceType,formRootDeptIds);
        int deptSize = CollectionUtils.isEmpty(departmentVOS) ? 0 : departmentVOS.size();
        int userSize = CollectionUtils.isEmpty(userSelectionVOS) ? 0 : userSelectionVOS.size();
        end = System.currentTimeMillis();
        log.info("process time9 : {}", end - start);
        log.info("process time total : {}", end - begin);
        return getOkResponseResult(new DepartmentUserTreeVO(departmentVOS, deptSize, userSelectionVOS, userSize), "查询用户信息成功");
    }

    private Map<String, List<DepartmentUserModel>> buildDepartmentUserMap(List<DepartmentUserModel> departmentUserList) {
        Map<String, List<DepartmentUserModel>> departmentUserMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(departmentUserList)) {
            departmentUserList.forEach(departmentUser -> {
                String key = departmentUser.getUserId();
                if (departmentUserMap.containsKey(key)) {
                    List<DepartmentUserModel> list = departmentUserMap.get(key);
                    list.add(departmentUser);
                } else {
                    List<DepartmentUserModel> list = new ArrayList<>();
                    list.add(departmentUser);
                    departmentUserMap.put(key, list);
                }
            });
        }
        return departmentUserMap;
    }

    private void setManagerAndSecretary(UserModel user, UserSelectionVO userSelectionVO, Map<String, UserModel> userMap, AtomicInteger count) {
        String managerId = user.getManagerId();
        if (!StringUtils.isBlank(managerId)) {
            UserModel manager = userMap.get(managerId);
            if (!userMap.containsKey(managerId)) {
                manager = getOrganizationFacade().getUser(managerId);
                count.incrementAndGet();
            }
            String userId = Optional.ofNullable(manager).map(UserModel::getId).orElse(null);
            String userName = Optional.ofNullable(manager).map(UserModel::getName).orElse(null);
            String imgUrl = Optional.ofNullable(manager).map(UserModel::getImgUrl).orElse(null);
            if (manager != null) {
                SelectionValue selectionValue = new SelectionValue();
                selectionValue.setType(UnitType.USER);
                selectionValue.setName(userName);
                selectionValue.setId(userId);
                selectionValue.setImgUrl(imgUrl);
                userSelectionVO.setManagerSelection(selectionValue);
                userMap.put(managerId, manager);
            }
        }
        String secretaryId = user.getSecretaryId();
        if (!StringUtils.isBlank(secretaryId)) {
            UserModel secretary = userMap.get(secretaryId);
            if (!userMap.containsKey(secretaryId)) {
                secretary = getOrganizationFacade().getUser(secretaryId);
                count.incrementAndGet();
            }
            String userId = Optional.ofNullable(secretary).map(UserModel::getId).orElse(null);
            String userName = Optional.ofNullable(secretary).map(UserModel::getName).orElse(null);
            String imgUrl = Optional.ofNullable(secretary).map(UserModel::getImgUrl).orElse(null);
            if (secretary != null) {
                SelectionValue selectionValue = new SelectionValue();
                selectionValue.setType(UnitType.USER);
                selectionValue.setName(userName);
                selectionValue.setId(userId);
                selectionValue.setImgUrl(imgUrl);
                userSelectionVO.setSecretary(selectionValue);
                userMap.put(secretaryId, secretary);
            }
        }
    }

    /**
     * 重复逻辑，临时解决方法
     *
     * @param allPathDeptSet
     * @param selectUserIds
     * @return
     */
    private Set<String> getLoginUserDeptPermAndSelectUsersMixed(Set<String> allPathDeptSet, String selectUserIds) {
        if (StringUtils.isBlank(selectUserIds)) {
            return null;
        }
        String[] split = selectUserIds.split(",");
        //用户的主部门和兼职部门
        List<DepartmentUserModel> departmentUserModels = new ArrayList<>();
        for (String userId : split) {
            //获得用户的主部门和兼职部门
            departmentUserModels.addAll(getOrganizationFacade().getDepartmentUsersByUserId(userId));
        }
        List<String> collect = departmentUserModels.stream().map(departmentUserModel -> departmentUserModel.getDeptId()).collect(Collectors.toList());
        Set<String> deptChildIdSet = getOrganizationFacade().getDepartmentsChildList(collect, false)
                .stream().map(DepartmentModel::getId).collect(Collectors.toSet());
        //取交集
        deptChildIdSet.retainAll(allPathDeptSet);
        return deptChildIdSet;
    }

    @GetMapping("/tree/ext/search")
    @ApiOperation(value = "选人控件根据名称搜索人或部门", notes = "选人控件根据名称搜索人或部门")
    @ApiImplicitParam(name = "name", value = "搜索名称", required = true, dataType = "String")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "搜索名称", required = true, dataType = "String"),
    })
    public ResponseResult<DepartmentUserTreeVO> searchExt(@RequestParam String name) {
        validateNotEmpty(name, "搜索名称不能为空");
        return getOkResponseResult(selectionHelperExt.searchDeptUser(name), "查询部门用户信息成功");
    }

    @ApiOperation(value = "根据 id 获取用户信息", notes = "根据用户名或账户名查询用户信息")
    @ApiImplicitParam(name = "id", value = "用户 id", required = true, dataType = "String", paramType = "query")
    @GetMapping("/info")
    public ResponseResult<UserDetailVO> info(@NotBlank(message = "用户 id 不能为空") @RequestParam String id) {
        UserModel user = getOrganizationFacade().getUser(id);
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtils.copyProperties(user, userDetailVO);
        List<RoleUserModel> roleUserModels = getOrganizationFacade().getRoleUsersByUserId(id);
        if (!CollectionUtils.isEmpty(roleUserModels)) {
            List<String> roleIds = roleUserModels.stream().map(RoleUserModel::getRoleId).collect(Collectors.toList());
            userDetailVO.setRoleIds(roleIds);
        }

        String departmentId = user.getDepartmentId();
        String deptPath = selectionHelper.getDeptPath(departmentId);

        //查询当前登录用户是否拥有应用权限，迭代36 加入
        AdminModel model = getAppAdminByUserId(getUserId(), true);
        if (StringUtils.isNotEmpty(departmentId)) {
            userDetailVO.setDepartmentId(departmentId);
            DepartmentModel department = getOrganizationFacade().getDepartment(departmentId);
            Map<String, Object> departmentName = Maps.newHashMap();
            departmentName.put("id", departmentId);
            departmentName.put("name", department.getName());
            departmentName.put("type", department.getUnitType());
            departmentName.put("operatable", checkLoginUserHasPermByDeptId(departmentId, model));
            departmentName.put("mainDeptPath", deptPath);

            userDetailVO.setMainDepartmentName(departmentName);
        }

        List<DepartmentUserModel> deptUsers = getOrganizationFacade().getDepartmentUsersByUserId(id);
        List<String> deptIds = deptUsers.stream().map(DepartmentUserModel::getDeptId).collect(Collectors.toList());
        deptIds.remove(departmentId);
        if (!CollectionUtils.isEmpty(deptIds)) {
            userDetailVO.setDeptIds(deptIds);
            List<Map<String, Object>> deptNames = Lists.newArrayList();
            for (String deptId : deptIds) {
                Map<String, Object> departmentName = Maps.newHashMap();
                DepartmentModel departmentModel = getOrganizationFacade().getDepartment(deptId);
                if (departmentModel != null) {
                    String name = departmentModel.getName();
                    departmentName.put("id", deptId);
                    departmentName.put("name", name);
                    departmentName.put("type", departmentModel.getUnitType());
                    departmentName.put("operatable", checkLoginUserHasPermByDeptId(deptId, model));
                    departmentName.put("mainDeptPath", deptPath);
                    deptNames.add(departmentName);
                }
            }
            userDetailVO.setDepartmentNames(deptNames);
        }

        if (StringUtils.isNotEmpty(user.getImgUrl())) {
            if (FileStorageConfiguration.getFileUploadType() == FileUploadType.OSS && !user.getImgUrl().startsWith("http")) {
                userDetailVO.setImgUrl(ossClient.buildDownloadUrlCatchException(user.getImgUrl()));
            }
        }
        userDetailVO.setGender(user.getGender());
        userDetailVO.setEntryDate(user.getEntryDate());
        //获取所属角色
        setRoleName(id, userDetailVO);
        //获取所属部门
        setDepartment(id, userDetailVO);
        //获取上级主管名称和秘书名称
        setManagerAndSecretary(user, userDetailVO);
        setRelatedInfo(userDetailVO);

        //获取已启动的拓展信息和设定好的组织
        List<UserExtAttrModel> userExtAttrModelList = dubboConfigService.getUserExtendFacade().getUserExtendByEnable(Short.parseShort("1"));
        List<UserExtAttrModel> userExtAttrList = new ArrayList<>();
        userExtAttrModelList.forEach(medel -> {
            if (medel.getCorpId().equals(user.getCorpId())) {
                UserUnionExtAttrModel userUnionExtAttrModel = dubboConfigService.getUserExtendFacade().getUnionExtAttrsByUserIdAndExtendAttrId(id, medel.getId());
                if (userUnionExtAttrModel != null) {
                    medel.setMapVal(userUnionExtAttrModel.getMapVal());
                    userExtAttrList.add(medel);
                } else {
                    userExtAttrList.add(medel);
                }
            }
        });
        userDetailVO.setUserExtAttrModels(userExtAttrList);
        return getOkResponseResult(userDetailVO, "根据 id 查询用户信息成功");
    }

    /**
     * 检查当前登录用户是否拥有操作指定部门的操作权限，有返回true，否则false
     *
     * @param deptId
     * @param adminModel
     * @return
     */
    private boolean checkLoginUserHasPermByDeptId(String deptId, AdminModel adminModel) {
        if (adminModel == null) {
            return false;
        }
        if (adminModel.getAdminType() == AdminType.ADMIN | adminModel.getAdminType() == AdminType.SYS_MNG) {
            return true;
        }
        if (adminModel.getAdminType() == AdminType.APP_MNG) {
            List<DepartmentScopeModel> departments = adminModel.getDepartments();
            if (CollectionUtils.isEmpty(departments)) {
                return false;
            }

            List<String> collect = departments.stream().map(departmentScopeModel -> departmentScopeModel.getUnitId()).collect(Collectors.toList());
            // 获取子部门数据
            List<DepartmentModel> allChildList = getOrganizationFacade().getDepartmentsChildList(collect);
            List<String> tempIdList = allChildList.stream().map(dept -> dept.getId()).collect(Collectors.toList());
            if (tempIdList.contains(deptId)) {
                return true;
            }
        }
        return false;
    }

    @ApiOperation(value = "根据 用户id 获取部门的主管信息", notes = "根据 用户id 获取部门的主管信息")
    @ApiImplicitParam(name = "userId", value = "用户 id", required = true, dataType = "String", paramType = "query")
    @GetMapping("/getDeptLeaderInfoByUserId")
    public ResponseResult getDeptLeaderInfoByUserId(@RequestParam String userId) {
        List<UserInfoVO> userInfoVOS = Lists.newArrayList();
        UserModel userModel = getOrganizationFacade().getUser(userId);
        if (userModel != null) {
            if (StringUtils.isNotEmpty(userModel.getDepartmentId())) {
                List<UserModel> userModels = getOrganizationFacade().getDeptManagersByDeptId(userModel.getDepartmentId());
                userInfoVOS = userModels.stream().map(item -> {
                    UserInfoVO userInfoVO = new UserInfoVO(item);
                    return userInfoVO;
                }).collect(Collectors.toList());
            } else {
                log.info("当前用户维护主部门关系不正确");
            }
        } else {
            log.info("当前用户实体不存在");
        }

        return getOkResponseResult(userInfoVOS, "根据用户id获取部门的主管信息成功");
    }

    @ApiOperation(value = "根据 部门 和 用户 id 获取家校用户信息", notes = "根据用户ID和部门ID查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "deptId", value = "部门ID", required = true, dataType = "String")
    })
    @GetMapping("/eduInfo")
    public ResponseResult eduInfo(@NotBlank(message = "用户 id 不能为空") @RequestParam String userId,
                                  @NotBlank(message = "部门 id 不能为空") @RequestParam String deptId) {
        UserModel user = getOrganizationFacade().getUser(userId);
        DepartmentModel departmentModel = getOrganizationFacade().getDepartment(deptId);
        if (user == null || departmentModel == null) {
            ErrCode errCode = ErrCode.ORG_USER_DEPT_EMPTY;
            return getErrResponseResult(errCode.getErrCode(), "用户或者部门实体不存在");
        }
        DepartmentModel classDept = getOrganizationFacade().getDepartment(departmentModel.getParentId());
        //关联关系
        DepartmentUserModel departmentUserModel = getOrganizationFacade().getDepartmentUserByDeptIdAndUserId(deptId, userId);
        if (departmentUserModel == null) {
            ErrCode errCode = ErrCode.ORG_USER_DEPT_EMPTY;
            return getErrResponseResult(errCode.getErrCode(), "用户和部门关联不存在");
        }

        EduUserDetailVO eduUserDetailVO = new EduUserDetailVO();
        BeanUtils.copyProperties(user, eduUserDetailVO);


        String departmentId = user.getDepartmentId();
        String deptPath = selectionHelper.getDeptPath(departmentId);

        //查询当前登录用户是否拥有应用权限，迭代36 加入
        AdminModel model = getAppAdminByUserId(getUserId(), true);
        if (StringUtils.isNotEmpty(departmentId)) {
            eduUserDetailVO.setDepartmentId(departmentId);
            DepartmentModel department = getOrganizationFacade().getDepartment(departmentId);
            Map<String, Object> departmentName = Maps.newHashMap();
            departmentName.put("id", departmentId);
            departmentName.put("name", department.getName());
            departmentName.put("type", department.getUnitType());
            departmentName.put("operatable", checkLoginUserHasPermByDeptId(departmentId, model));
            departmentName.put("mainDeptPath", deptPath);
            eduUserDetailVO.setMainDepartmentName(departmentName);
        }

        //获取所属角色
        setRoleName(userId, eduUserDetailVO);
        //获取所属部门
        setDepartment(userId, eduUserDetailVO);
        //获取上级主管名称和秘书名称
        setManagerAndSecretary(user, eduUserDetailVO);
        if (DingTalkUrlConstants.DEPT_STUDENT.equals(departmentModel.getExtend3())) {
            //学生信息(班级，家长)
            eduUserDetailVO.setTag(DingTalkUrlConstants.DEPT_STUDENT);
            eduUserDetailVO.setStudentClassName(getClassPathName(deptId));

            //家长所在部门
            List<DepartmentModel> classChildDepts = getOrganizationFacade().getDepartmentsByParentId(classDept.getId());
            List<DepartmentModel> guardianDept = classChildDepts.stream().filter(item -> DingTalkUrlConstants.DEPT_GUARDIAN.equals(item.getName())).collect(Collectors.toList());
            List<DepartmentUserModel> deptUsers = getOrganizationFacade().getParentsDeptUserByStudentIds(ImmutableList.of(userId));
            if (!CollectionUtils.isEmpty(deptUsers)) {
                Map<String, String> deptUserMaps = deptUsers.stream().collect(Collectors.toMap(
                        DepartmentUserModel::getUserId,
                        DepartmentUserModel::getDeptId
                ));
                if (!CollectionUtils.isEmpty(deptUsers)) {
                    List<EduClassUserInfoVO> guardians = Lists.newArrayList();
                    deptUsers.forEach(item -> {
                        UserModel userModel = getOrganizationFacade().getUser(item.getUserId());
                        if (userModel != null) {
                            EduClassUserInfoVO vo = new EduClassUserInfoVO();
                            BeanUtils.copyProperties(userModel, vo);
                            if (CollectionUtils.isEmpty(guardianDept)) {
                                vo.setDeptId(deptUserMaps.get(userModel.getId()));
                            } else {
                                vo.setDeptId(guardianDept.get(0).getId());
                            }
                            guardians.add(vo);
                        }
                    });
                    eduUserDetailVO.setGuardians(guardians);
                }
            }

        } else if (DingTalkUrlConstants.DEPT_TEACHER.equals(departmentModel.getExtend3())) {
            //老师信息
            eduUserDetailVO.setTag(DingTalkUrlConstants.DEPT_TEACHER);
            //查询老师所在的班级
            List<DepartmentModel> tearchClasss = getOrganizationFacade().getDepartmentsByUserId(userId, Boolean.TRUE);
            if (!CollectionUtils.isEmpty(tearchClasss)) {
                tearchClasss = tearchClasss.stream().filter(item -> DingTalkUrlConstants.DEPT_TEACHER.equals(item.getName())).collect(Collectors.toList());
                List<EduClassUserInfoVO> tearchvos = Lists.newArrayList();
                tearchClasss.forEach(item -> {
                    EduClassUserInfoVO vo = new EduClassUserInfoVO();
                    vo.setDeptId(item.getId());
                    vo.setDeptName(getClassPathName(item.getId()));
                    vo.setIsAdviser(getClassAdviser(item.getId(), userId));
                    tearchvos.add(vo);
                });
                eduUserDetailVO.setTearchers(tearchvos);
            }

            eduUserDetailVO.setChildrens(getChildrenClass(user));

        } else if (DingTalkUrlConstants.DEPT_GUARDIAN.equals(departmentModel.getExtend3())) {
            //家长信息
            eduUserDetailVO.setTag(DingTalkUrlConstants.DEPT_GUARDIAN);
            eduUserDetailVO.setChildrens(getChildrenClass(user));
        }
        return getOkResponseResult(eduUserDetailVO, " 查询家校用户信息成功");
    }

    private List<EduClassUserInfoVO> getChildrenClass(UserModel user) {
        List<EduClassUserInfoVO> childrens = Lists.newArrayList();
        //获取当前用户的所有部门信息
        List<DepartmentUserModel> departmentUserModels = getOrganizationFacade().getDepartmentUsersByUserId(user.getId());
        if (!CollectionUtils.isEmpty(departmentUserModels)) {
            departmentUserModels = departmentUserModels.stream().filter(item -> {
                return StringUtils.isNotBlank(item.getUserSourceId()) && StringUtils.isNotBlank(item.getRemarks()) && item.getRemarks().startsWith(DingTalkUrlConstants.EDU_STUDENT_REMARK);
            })
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(departmentUserModels)) {
                Set<String> childsIdSets = departmentUserModels.stream().map(DepartmentUserModel::getUserSourceId).collect(Collectors.toSet());
                childsIdSets.forEach(userId -> {
                    List<DepartmentModel> childDepts = getOrganizationFacade().getDepartmentsByUserId(userId);
                    if (!CollectionUtils.isEmpty(childDepts)) {
                        UserModel userModel = getOrganizationFacade().getUser(userId);
                        List<DepartmentModel> childrenDeptSet = childDepts.stream().filter(item -> DingTalkUrlConstants.DEPT_STUDENT.equals(item.getName())).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(childrenDeptSet)) {
                            //一个学生只会出现在一个
                            DepartmentModel departmentModel = childrenDeptSet.get(0);
                            EduClassUserInfoVO userInfoVO = new EduClassUserInfoVO();
                            userInfoVO.setId(userId);
                            userInfoVO.setUserId(userModel.getUserId());
                            userInfoVO.setName(userModel.getName());
                            userInfoVO.setDeptId(departmentModel.getId());
                            userInfoVO.setDeptName(getClassPathName(departmentModel.getId()));
                            childrens.add(userInfoVO);
                        }
                    }
                });
            }
        }

        return childrens;
    }

    private Boolean getClassAdviser(String deptId, String userId) {
        Boolean isAdviser = false;
        DepartmentUserModel departmentUserModel = getOrganizationFacade().getDepartmentUserByDeptIdAndUserId(deptId, userId);
        if (departmentUserModel != null) {
            isAdviser = Boolean.TRUE.equals(departmentUserModel.getMain());
        }
        return isAdviser;
    }

    private String getClassPathName(String deptId) {
        String classPathName = "";
        List<DepartmentModel> parentDepts = getOrganizationFacade().getParentDepartments(deptId, Boolean.TRUE);
        if (!CollectionUtils.isEmpty(parentDepts)) {
            Collections.reverse(parentDepts);
            if (parentDepts.size() > 3) {
                parentDepts = parentDepts.subList(2, parentDepts.size());
            }
            List<String> eduClassName = parentDepts.stream().map(item -> item.getName()).collect(Collectors.toList());
            classPathName = StringUtils.join(eduClassName, "/");
        }
        return classPathName;
    }

    /**
     * @return departmentList
     * @Description: 通过id获取部门列表
     * @Param [Id, ]
     * @author Liuqingshan
     * @date 2019/6/10 11:08
     */
    @ApiOperation(value = "根据 id 获取部门列表", notes = "根据用户id查询部门列表")
    @ApiImplicitParam(name = "id", value = "用户 id", required = true, dataType = "String", paramType = "query")
    @GetMapping("/departments")
    public ResponseResult<List<Map<String, Object>>> getDepartmentList(@NotBlank(message = "用户 id 不能为空") @RequestParam String id, @RequestParam(required = false) String filterType) {
        //拿到部门列表
        List<DepartmentModel> departments = getOrganizationFacade().getDepartmentsByUserId(id);
        List<Map<String, Object>> result = Lists.newArrayList();
        //非空
        if (!CollectionUtils.isEmpty(departments)) {
            UserModel user = getOrganizationFacade().getUser(id);
            String mainDepartmentId = user.getDepartmentId();
            departments = departments.stream().filter(item -> Boolean.TRUE.equals(item.getIsShow())).collect(Collectors.toList());
            Set<String> managePermChildDepartment;
            boolean needFilter = false;
            if (StringUtils.isNotEmpty(filterType) && "admin".equals(filterType)) {
                AdminModel appAdminByUser = getAppAdminByUserId(getUserId());
                if (appAdminByUser != null && appAdminByUser.getAdminType() == AdminType.APP_MNG) {
                    managePermChildDepartment = getManagePermChildDepartmentId(getUserId());
                    needFilter = true;
                } else {
                    managePermChildDepartment = new HashSet<>();
                }
            } else {
                managePermChildDepartment = new HashSet<>();
            }

            boolean finalNeedFilter = needFilter;
            List<String> IdList = departments
                    .stream().filter(dept -> finalNeedFilter ?
                            Objects.nonNull(dept) && managePermChildDepartment.contains(dept.getId()) : Objects.nonNull(dept)).map(DepartmentModel::getId).collect(Collectors.toList());
            //
            for (String deptId : IdList) {
                Map<String, Object> deptMap = new HashMap<>();
                DepartmentModel department = getOrganizationFacade().getDepartment(deptId);
                String deptName;
                if (StringUtils.isNotBlank(department.getQueryCode()) && department.getQueryCode().startsWith("1#-7#")) {
                    //家校虚拟部门处理
                    if (Boolean.FALSE.equals(department.getIsShow())) {
                        continue;
                    }
                    DepartmentModel parent = getOrganizationFacade().getDepartment(department.getParentId());
                    deptName = parent.getName() + "-" + department.getName();
                } else {
                    deptName = department.getName();
                }
                deptMap.put("deptId", department.getId());
                deptMap.put("isMain", Objects.equals(mainDepartmentId, department.getId()));
                String deptPath = selectionHelper.getDeptPath(deptId);
                deptMap.put("deptName", deptPath);
                result.add(deptMap);
            }
        }
        return getOkResponseResult(result, "根据 id 查询部门列表成功");
    }

    /**
     * @return void
     * @Description: 默认状态之下管理员修改用户主部门
     * @Param [departmentUserModel]
     * @author Liuqingshan
     * @date 2019/6/10 11:08
     */
    @PutMapping("/update_main")
    @ApiOperation(value = "修改部门用户所属主部门", notes = "修改部门用户的主部门")
    public ResponseResult<UserDetailVO> updateMain(@RequestBody DepartmentUserVO departmentUserVO) {
        validateNotEmpty(departmentUserVO.getUserId(), "用户id不能为空");
        validateNotEmpty(departmentUserVO.getDeptId(), "部门id不能为空");
        String id = departmentUserVO.getUserId();
        //id非空
        if (StringUtils.isNotEmpty(id)) {
            //拿到用户
            UserModel user = getOrganizationFacade().getUser(id);
            //拿到用户部门列表
            List<DepartmentUserModel> deptUserList = getOrganizationFacade().getDepartmentUsersByUserId(id);

            List<DepartmentUserModel> collect = deptUserList.stream().filter(t -> t.getMain()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                for (DepartmentUserModel departmentUserModel : collect) {
                    departmentUserModel.setMain(false);
                    getOrganizationFacade().updateDeptUser(departmentUserModel);
                }
            }
            List<DepartmentUserModel> departModels = deptUserList.stream().filter(t -> t.getDeptId().equals(departmentUserVO.getDeptId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(departModels)) {
                return getOkResponseResult(null, "修改用户主部门失败");
            }
            DepartmentUserModel departmentUserModel = departModels.get(0);

            user.setDepartmentId(departmentUserModel.getDeptId());
            UserModel userModel = getOrganizationFacade().updateUser(user);
            UserDetailVO userDetailVO = new UserDetailVO();
            userDetailVO.setDepartmentId(user.getDepartmentId());
            userDetailVO.setDepartmentName(getOrganizationFacade().getDepartment(departmentUserModel.getDeptId()).getName());
            userDetailVO.setName(userModel.getName());
            return getOkResponseResult(userDetailVO, "修改用户主部门成功");
        }
        return getOkResponseResult(null, "修改用户主部门是失败");
    }

    /**
     * @return void
     * @Description: 设置上级主管和秘书名称
     * @Param [user, userDetailVO]
     * @author dengchao
     * @date 2018/11/2 1:01
     */
    private void setManagerAndSecretary(UserModel user, UserDetailVO userDetailVO) {
        String managerId = user.getManagerId();
        if (!StringUtils.isBlank(managerId)) {
            UserModel manager = getOrganizationFacade().getUser(managerId);
            if (manager != null) {
                userDetailVO.setManagerName(manager.getName());
            }
        }
        String secretaryId = user.getSecretaryId();
        if (!StringUtils.isBlank(secretaryId)) {
            UserModel secretary = getOrganizationFacade().getUser(secretaryId);
            if (secretary != null) {
                userDetailVO.setSecretaryName(secretary.getName());
            }
        }
    }

    /**
     * @return void
     * @Description: 设置所属部门名称
     * @Param [id, userDetailVO]
     * @author dengchao
     * @date 2018/11/1 14:45
     */
    private void setDepartment(String id, UserDetailVO userDetailVO) {
        List<DepartmentModel> departmentList = getOrganizationFacade().getDepartmentsByUserId(id);
        if (!CollectionUtils.isEmpty(departmentList)) {
            List<String> departmentNameList = Lists.newArrayList();
            departmentList = departmentList.stream().filter(item -> Boolean.TRUE.equals(item.getIsShow())).collect(Collectors.toList());
            for (DepartmentModel dept : departmentList) {
                if (dept == null) {
                    continue;
                }
                if (StringUtils.isNotBlank(dept.getQueryCode()) && dept.getQueryCode().startsWith("1#-7#")) {
                    String deptName;
                    DepartmentModel parent = getOrganizationFacade().getDepartment(dept.getParentId());
                    if (parent != null) {
                        deptName = parent.getName() + "-" + dept.getName();
                    } else {
                        deptName = dept.getName();
                    }
                    departmentNameList.add(deptName);
                } else {
                    departmentNameList.add(dept.getName());
                }
            }

            userDetailVO.setDepartmentName(String.join(",", departmentNameList));
            List<DepartmentModel> mainDept = departmentList.stream().filter(item -> item.getId().equals(userDetailVO.getDepartmentId())).collect(Collectors.toList());
            Boolean isShool = Boolean.FALSE;
            if (!CollectionUtils.isEmpty(mainDept)) {
                String queryCode = mainDept.get(0).getQueryCode();
                if (StringUtils.isNotBlank(queryCode) && queryCode.startsWith("1#-7#")) {
                    isShool = Boolean.TRUE;
                }
            }
            userDetailVO.setIsHomeSchool(isShool);
        }
    }

    /**
     * @return void
     * @Description: 设置所属角色
     * @Param [id, userDetailVO]
     * @author dengchao
     * @date 2018/11/1 14:45
     */
    private void setRoleName(String id, UserDetailVO userDetailVO) {
        List<String> idList = ImmutableList.of(id);
        Map<String, List<RoleModel>> roleMap = getOrganizationFacade().getRolesByUserIds(idList);
        List<RoleModel> roleList = null;
        if (roleMap != null) {
            roleList = roleMap.get(id);
        }
        if (roleList != null) {
            List<String> roleNameList = roleList
                    .stream().filter(Objects::nonNull).map(RoleModel::getName).collect(Collectors.toList());
            if (!roleNameList.isEmpty()) {
                userDetailVO.setRoleName(String.join(",", roleNameList));
            }
        }
    }

    /**
     * @return UserVO
     * @Description: 添加所属角色字段
     * @Param [pageable, userPage]
     * @author dengchao
     * @date 2018/11/1 14:46
     */
    private void setRoleName(List<UserVO> userVOList) {
        //添加所属角色字段
        List<String> idList = userVOList
                .stream().filter(Objects::nonNull).map(BaseModel::getId).collect(Collectors.toList());
        Map<String, List<RoleModel>> roleNameMap;
        if (!idList.isEmpty()) {
            roleNameMap = getOrganizationFacade().getRolesByUserIds(idList);
            if (!CollectionUtils.isEmpty(roleNameMap)) {
                userVOList.forEach(userVO -> {
                    List<RoleModel> roleList = roleNameMap.get(userVO.getId());
                    if (!CollectionUtils.isEmpty(roleList)) {
                        List<String> roleNameList = roleList.stream().filter(Objects::nonNull).map(RoleModel::getName).collect(Collectors.toList());
                        userVO.setRoleName(String.join(",", roleNameList));
                    }
                });
            }
        }
    }

    @ApiOperation(value = "查询当前登录用户信息", notes = "解析请求头，查询用户信息")
    @GetMapping("/info_login")
    public ResponseResult<UserDetailVO> userInfo() {
        String userId = getUserId();
        UserModel userModel = getOrganizationFacade().getUser(userId);
        if (Objects.isNull(userModel)) {
            throw new PortalException(ErrCode.ORG_USER_NONEXISTENT);
        }
        String departmentId = userModel.getDepartmentId();
        DepartmentModel department = getOrganizationFacade().getDepartment(departmentId);
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtils.copyProperties(userModel, userDetailVO);

        String imgUrl = userModel.getImgUrl();
        if (StringUtils.isNotEmpty(imgUrl)) {
            if (imgUrl.startsWith("http:") || imgUrl.startsWith("https:")) {
                userDetailVO.setImgUrl(imgUrl);
            } else if (FileStorageConfiguration.getFileUploadType() == FileUploadType.OSS) {
                userDetailVO.setImgUrl(ossClient.buildDownloadUrlCatchException(imgUrl));
            }
        }

        userDetailVO.setDepartmentName(Optional.ofNullable(department).map(DepartmentModel::getName).orElse(null));

        setRelatedInfo(userDetailVO);
        setRoleName(userId, userDetailVO);

        List<AdminModel> admins = this.getPermissionManagementFacade().getAdminByUserId(userId);
        if (!CollectionUtils.isEmpty(admins)) {
            admins.stream().filter(Objects::nonNull).forEach(adminModel -> {
                if (adminModel.getAdminType() != null) {
                    userDetailVO.addPermssion(adminModel.getAdminType().name());
                }
            });
        }
        return getOkResponseResult(userDetailVO, "获取当前登录用户信息成功");
    }

    private void setRelatedInfo(UserDetailVO userDetailVO) {
        if (StringUtils.isNotEmpty(userDetailVO.getCorpId())) {
            RelatedCorpSettingModel relatedCorpSettingModel = getSystemManagementFacade().getRelatedCorpSettingModelByCorpId(userDetailVO.getCorpId());
            if (relatedCorpSettingModel != null) {
                userDetailVO.setRelatedOrgType(relatedCorpSettingModel.getOrgType());
                userDetailVO.setRelatedSyncType(relatedCorpSettingModel.getSyncType());
                userDetailVO.setPcServerUrl(relatedCorpSettingModel.getPcServerUrl());
                userDetailVO.setMobileServerUrl(relatedCorpSettingModel.getMobileServerUrl());
                userDetailVO.setAgentId(relatedCorpSettingModel.getAgentId());
                userDetailVO.setRelatedType(relatedCorpSettingModel.getRelatedType());
            }
        }

    }

    @ApiOperation(value = "查询用户总人数", notes = "查询用户总人数")
    @GetMapping("/total_num")
    public ResponseResult<Integer> getTotalNum() {
        Integer totalNum = getOrganizationFacade().countUser();
        return getOkResponseResult(totalNum, "查询用户总人数成功");
    }

    @ApiOperation(value = "根据用户名查找用户", notes = "根据用户名查找用户")
    @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query")
    @GetMapping("/get_by_username")
    public ResponseResult<UserModel> getByUsername(String username) {

        UserModel userModel = getOrganizationFacade().getUserByUserNameAndCorpId(username, getMainCorpId());
        if (userModel == null) {
            return getErrResponseResult(userModel, ErrCode.ORG_USER_NONEXISTENT.getErrCode(), "用户不存在");
        }
        return getOkResponseResult(userModel, "根据用户名查询用户信息成功");
    }

    @ApiOperation(value = "修改超管密码", notes = "根据传入的用户名和用户密码修改管理员密码")
    @ApiImplicitParam(name = "params", value = "{\"username\":\"账号\",\"oldPassword\":\"原密码\",\"newPassword\":新密码}", required = true, dataType = "Map")
    @PutMapping("/modify_password_by_username")
    public ResponseResult<AdministratorVO> modifyPassword(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");


        if (StringUtils.isEmpty(username)) {
            log.info("输入的账号参数为空");
            return null;
        }
        if ("admin".equals(username)) {
            UserModel entity = getOrganizationFacade().getUserByUserNameAndCorpId(username, getMainCorpId());
            if (null == entity) {
                log.info("查询超级管理员不存在");
                return null;
            }
            String password = entity.getPassword();
            if (StringUtils.isEmpty(oldPassword)) {
                log.info("输入的密码为空");
                return null;
            }
            PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            boolean matches = encoder.matches(oldPassword, password);
            AdministratorVO adminVO = new AdministratorVO();
            adminVO.setUsername(entity.getUsername());
            if (matches) {
                if (StringUtils.isEmpty(newPassword)) {
                    log.info("输入的新密码为空");
                    return null;
                }
                boolean matches1 = encoder.matches(newPassword, password);
                if (matches1) {
                    return getErrResponseResult(adminVO, ErrCode.ORG_USER_PASSWORD_CONSISTENT.getErrCode(), ErrCode.ORG_USER_PASSWORD_CONSISTENT.getErrMsg());
                }
                String newPswd = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(newPassword);
                entity.setPassword(newPswd);
                UserModel admin = getOrganizationFacade().updateUser(entity);
                adminVO.setUsername(admin.getUsername());
                return getOkResponseResult(adminVO, "根据用户账号修改密码成功");
            } else {
                return getErrResponseResult(adminVO, ErrCode.ORG_USER_PASSWORD_INCONSISTENT.getErrCode(), ErrCode.ORG_USER_PASSWORD_INCONSISTENT.getErrMsg());

            }
        }
        log.info("输入的参数不符合规定");
        return null;
    }

    @ApiOperation(value = "用户导入接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/import_data")
    public ResponseResult<FileOperationResult> importUserData(@NotBlank(message = "文件名称不能为空") @RequestParam String fileName) {
        String userId = this.getUserId();
        log.debug("用户id为={}", userId);
        FileOperationResult fileOperationResult = new FileOperationResult();
        String[] fileNameArray = fileName.split("\\.");
        if (!"xlsx".equals(fileNameArray[1]) && !"xls".equals(fileNameArray[1])) {
            fileOperationResult.setErrorType(2);
            fileOperationResult.setOperationResult(false);
            fileOperationResult.setErrorMsg("不支持的导入格式");
            return this.getOkResponseResult(fileOperationResult, "操作失败");
        }

        fileOperationResult.setSuccessCount(0);
        fileOperationResult.setErrorCount(0);
        fileOperationResult.setOperationResult(true);

        springThreadTask.importUsers(userId, fileName);
        return this.getOkResponseResult(fileOperationResult, "操作成功");
    }

    @PostMapping("/add")
    @ApiOperation(value = "云枢维护创建用户", notes = "云枢维护创建用户")
    @ApiImplicitParam(name = "userVO", value = "{\"departmentId\":\"主部门ID\",\"deptIds\":\"兼职部门ID集合\",\"username\":\"用户账号\",\"name\":\"用户姓名\"," +
            "\"roleIds\":\"角色ID集合\",\"mobile\":\"手机号\",\"officePhone\":\"办公电话\",\"email\":\"邮箱\",\"employeeNo\":\"员工编号\",\"entryDate\":\"入职时间\",\"imgUrl\":\"头像url\",\"imgUrlId\":\"头像Id\",\"gender\":\"性别\"}", dataType = "UserVO", defaultValue = "")
    public ResponseResult<UserVO> createdUser(@RequestBody UserVO userVO) {
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        return userHelper.create(userVO);
    }

    @PostMapping("/modify")
    @ApiOperation(value = "云枢维护编辑用户", notes = "云枢维护编辑用户")
    @ApiImplicitParam(name = "userVO", value = "{\"departmentId\":\"主部门ID\",\"deptIds\":\"兼职部门ID集合\",\"username\":\"用户账号\",\"name\":\"用户姓名\"," +
            "\"roleIds\":\"角色ID集合\",\"mobile\":\"手机号\",\"officePhone\":\"办公电话\",\"email\":\"邮箱\",\"employeeNo\":\"员工编号\",\"entryDate\":\"入职时间\"," +
            "\"id\":\"用户主键id\",\"imgUrl\":\"头像url\",\"imgUrlId\":\"头像Id\",\"gender\":\"性别\",\"UserUnionExtAttrModel\":\"拓展信息\"}", dataType = "UserVO", defaultValue = "")
    public ResponseResult<UserVO> modifiedUser(@RequestBody UserVO userVO) {
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        return userHelper.modified(userVO);
    }

    @GetMapping("/strike_out")
    @ApiOperation(value = "云枢维护删除用户", notes = "云枢维护删除用户")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "String", defaultValue = "")
    public ResponseResult<String> strikeOutUser(@RequestParam String id) {
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        return userHelper.delete(id);
    }

    @ApiOperation(value = "重置密码", notes = "管理员重置密码")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "String")
    @GetMapping("/reset_password")
    public ResponseResult<UserVO> resetPassword(@RequestParam String id) {
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        return userHelper.reset(id);
    }

    @ApiOperation(value = "用户数据模板导出接口")
    @GetMapping("/export_template")
    public void exportTemplate(HttpServletResponse response) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("userId", "");
        map.put("userName", "");
        map.put("mobile", "");
        map.put("mainDept", "请输入部门全路径；如：深圳xx公司/研发中心/xx研发");
        map.put("depts", "请输入部门全路径；如：深圳xx公司/研发中心/xx研发；多个部门请用“;”分隔");
        map.put("roles", "多个角色请用“;”分割，“部门主管”角色不支持导入");
        map.put("email", "");
        map.put("officePhone", "");
        map.put("employeeNo", "");
        map.put("entryDate", "");

        Map<String, Object> map2 = new LinkedHashMap<>();
        map2.put("userId", "test1");
        map2.put("userName", "测试用户");
        map2.put("mobile", "13800138000（示例）");
        map2.put("mainDept", "深圳xx公司/研发中心/xx研发");
        map2.put("depts", "深圳xx公司/研发中心/xx研发;深圳xx公司/研发中心/yy研发");
        map2.put("roles", "财务;测试");
        map2.put("email", "abfdghjc@gmail.com");
        map2.put("officePhone", "0755-8888888");
        map2.put("employeeNo", "AB001");
        map2.put("entryDate", "2020-01-01");

        List<Map<String, Object>> datas = new ArrayList<>();
        datas.add(map);
        datas.add(map2);

        FileOperateHelper.exportData(response, Lists.newArrayList("用户账号", "用户姓名", "手机号码", "所属主部门", "兼职部门", "角色", "邮箱", "办公电话", "员工编号", "入职时间")
                , "账户", datas, null, false);
    }

    @GetMapping("/listManagerConfig")
    @ApiOperation(value = "查询用户直属主管列表", notes = "查询用户直属主管列表")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String")
    public ResponseResult<List<UserManagerVO>> listManagerConfig(@RequestParam String userId) {
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        return userHelper.listManagerConfig(userId);
    }

}
